import { reqLoginAccount, reqLoginOut } from "@/api"

const state = {
  userList: {
    //   直接从内存值取出
    name: localStorage.getItem("name"),
    token: localStorage.getItem("token"),
  },
}
const actions = {
  // 登录
  async getLoginAccount({ commit }, user) {
    console.log(user)
    const result = await reqLoginAccount(user)
    // 获取到了数据,往内存中存一份
    localStorage.setItem("token", result.data.token)
    localStorage.setItem("name", result.data.name)
    commit("GET_LOGIN_ACCOUNT", result.data)
  },
  // 退出登录
  async getLoginOut({ commit }) {
    await reqLoginOut()
    localStorage.removeItem("name")
    localStorage.removeItem("token")
    commit("REMOVE_USER_INFO")
  },
}
const mutations = {
  // 登录
  GET_LOGIN_ACCOUNT(state, payload) {
    state.userList.name = payload.name
    state.userList.token = payload.token

    // if (payload.code == 200) {
    //   // alert("登录成功")
    //   this.$router.push("/home")
    //   // 成功后跳转到主页面
    //   // 第一将获取的token存入vuex和loaclstory, 第二将header组件中的左侧导航换成用户名
    // }
    // }
  },
  // 退出登录
  REMOVE_USER_INFO(state, payload) {
    state.userList.name = ""
    state.userList.token = ""
  },
}
const getters = {}
export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
}
